<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  DescriptionsItem,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 状态管理
const loading = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const showAssignModal = ref(false);
const isEdit = ref(false);
const selectedWorkOrder = ref(null);

// 表单引用
const formRef = ref();
const assignFormRef = ref();

// 统计数据
const statistics = reactive({
  totalWorkOrders: 156,
  totalChange: 12,
  pendingWorkOrders: 23,
  pendingChange: -5,
  processingWorkOrders: 8,
  processingChange: 3,
  completedWorkOrders: 125,
  completedChange: 8,
});

// 搜索表单
const searchForm = reactive({
  workOrderNumber: '',
  roomNumber: '',
  type: '',
  status: '',
  priority: '',
});

// 工单表单
const form = reactive({
  roomNumber: '',
  type: '',
  priority: 'medium',
  estimatedTime: null,
  description: '',
  contactPerson: '',
  contactPhone: '',
  remark: '',
});

// 分配表单
const assignForm = reactive({
  technicianId: '',
  startTime: null,
  assignRemark: '',
});

// 表单验证规则
const rules = {
  roomNumber: [{ required: true, message: '请选择房间号' }],
  type: [{ required: true, message: '请选择报修类型' }],
  priority: [{ required: true, message: '请选择优先级' }],
  description: [{ required: true, message: '请描述问题' }],
  contactPerson: [{ required: true, message: '请输入联系人' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
};

const assignRules = {
  technicianId: [{ required: true, message: '请选择维修人员' }],
  startTime: [{ required: true, message: '请选择开始时间' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 可用房间
const availableRooms = ref([
  { id: 1, roomNumber: '101' },
  { id: 2, roomNumber: '102' },
  { id: 3, roomNumber: '201' },
  { id: 4, roomNumber: '202' },
  { id: 5, roomNumber: '301' },
]);

// 可用维修人员
const availableTechnicians = ref([
  { id: 1, name: '张师傅', specialty: ['电气', '家电'] },
  { id: 2, name: '李师傅', specialty: ['水管', '结构'] },
  { id: 3, name: '王师傅', specialty: ['家具', '家电'] },
  { id: 4, name: '赵师傅', specialty: ['电气', '水管'] },
]);

// 工单数据
const workOrders = ref([
  {
    id: 1,
    workOrderNumber: 'WO-2024-001',
    roomNumber: '101',
    type: 'electrical',
    priority: 'high',
    status: 'pending',
    description: '空调不制冷，需要检查制冷系统',
    contactPerson: '张三',
    contactPhone: '13800138001',
    technician: null,
    createdAt: '2024-01-15 09:30',
    estimatedTime: '2024-01-16',
    remark: '客户反映空调完全不制冷',
  },
  {
    id: 2,
    workOrderNumber: 'WO-2024-002',
    roomNumber: '205',
    type: 'plumbing',
    priority: 'medium',
    status: 'assigned',
    description: '水龙头漏水，需要更换密封圈',
    contactPerson: '李四',
    contactPhone: '13800138002',
    technician: '张师傅',
    createdAt: '2024-01-15 10:15',
    estimatedTime: '2024-01-15',
    remark: '轻微漏水，不影响使用',
  },
  {
    id: 3,
    workOrderNumber: 'WO-2024-003',
    roomNumber: '302',
    type: 'appliance',
    priority: 'low',
    status: 'processing',
    description: '电视遥控器失灵，需要更换电池或遥控器',
    contactPerson: '王五',
    contactPhone: '13800138003',
    technician: '李师傅',
    createdAt: '2024-01-15 11:00',
    estimatedTime: '2024-01-15',
    remark: '已尝试更换电池，问题依然存在',
  },
  {
    id: 4,
    workOrderNumber: 'WO-2024-004',
    roomNumber: '401',
    type: 'furniture',
    priority: 'medium',
    status: 'completed',
    description: '衣柜门把手松动，需要紧固',
    contactPerson: '赵六',
    contactPhone: '13800138004',
    technician: '王师傅',
    createdAt: '2024-01-14 14:30',
    estimatedTime: '2024-01-14',
    remark: '已完成维修',
  },
]);

// 表格列定义
const columns = [
  {
    title: '工单号',
    dataIndex: 'workOrderNumber',
    key: 'workOrderNumber',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '报修类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 80,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '维修人员',
    dataIndex: 'technician',
    key: 'technician',
    width: 100,
  },
  {
    title: '联系人',
    dataIndex: 'contactPerson',
    key: 'contactPerson',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 过滤后的工单数据
const filteredWorkOrders = computed(() => {
  let result = workOrders.value;

  if (searchForm.workOrderNumber) {
    result = result.filter((item) =>
      item.workOrderNumber
        .toLowerCase()
        .includes(searchForm.workOrderNumber.toLowerCase()),
    );
  }

  if (searchForm.roomNumber) {
    result = result.filter((item) =>
      item.roomNumber.includes(searchForm.roomNumber),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.priority) {
    result = result.filter((item) => item.priority === searchForm.priority);
  }

  return result;
});

// 状态和类型相关函数
const getStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    assigned: 'blue',
    processing: 'green',
    completed: 'green',
    cancelled: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts = {
    pending: '待处理',
    assigned: '已分配',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消',
  };
  return texts[status] || status;
};

const getPriorityColor = (priority: string) => {
  const colors = {
    low: 'green',
    medium: 'blue',
    high: 'orange',
    urgent: 'red',
  };
  return colors[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
  };
  return texts[priority] || priority;
};

const getTypeColor = (type: string) => {
  const colors = {
    electrical: 'blue',
    plumbing: 'cyan',
    appliance: 'purple',
    furniture: 'orange',
    structure: 'red',
    other: 'default',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts = {
    electrical: '电气维修',
    plumbing: '水管维修',
    appliance: '家电维修',
    furniture: '家具维修',
    structure: '结构维修',
    other: '其他',
  };
  return texts[type] || type;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    workOrderNumber: '',
    roomNumber: '',
    type: '',
    status: '',
    priority: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    if (isEdit.value) {
      message.success('工单更新成功');
    } else {
      message.success('工单创建成功');
    }
    showAddModal.value = false;
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  showAddModal.value = false;
  resetForm();
};

const handleAssign = async () => {
  try {
    await assignFormRef.value.validate();
    message.success('工单分配成功');
    showAssignModal.value = false;
    resetAssignForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const viewDetail = (record: any) => {
  selectedWorkOrder.value = record;
  showDetailModal.value = true;
};

const editWorkOrder = (record: any) => {
  isEdit.value = true;
  Object.assign(form, record);
  showAddModal.value = true;
};

const assignWorkOrder = (record: any) => {
  selectedWorkOrder.value = record;
  showAssignModal.value = true;
};

const startWorkOrder = (record: any) => {
  message.success(`工单 ${record.workOrderNumber} 已开始处理`);
};

const completeWorkOrder = (record: any) => {
  message.success(`工单 ${record.workOrderNumber} 已完成`);
};

const resetForm = () => {
  Object.assign(form, {
    roomNumber: '',
    type: '',
    priority: 'medium',
    estimatedTime: null,
    description: '',
    contactPerson: '',
    contactPhone: '',
    remark: '',
  });
  isEdit.value = false;
};

const resetAssignForm = () => {
  Object.assign(assignForm, {
    technicianId: '',
    startTime: null,
    assignRemark: '',
  });
};

onMounted(() => {
  // 初始化数据
  pagination.total = workOrders.value.length;
});
</script>

<template>
  <div class="work-orders-management">
    <div class="page-header">
      <h2>维修工单管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建工单
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总工单数"
          :value="statistics.totalWorkOrders"
          :change="statistics.totalChange"
          icon="ant-design:file-text-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="待处理"
          :value="statistics.pendingWorkOrders"
          :change="statistics.pendingChange"
          icon="ant-design:clock-circle-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="处理中"
          :value="statistics.processingWorkOrders"
          :change="statistics.processingChange"
          icon="ant-design:tool-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成"
          :value="statistics.completedWorkOrders"
          :change="statistics.completedChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <FormItem label="工单号">
          <Input
            v-model:value="searchForm.workOrderNumber"
            placeholder="请输入工单号"
            allow-clear
          />
        </FormItem>
        <FormItem label="房间号">
          <Input
            v-model:value="searchForm.roomNumber"
            placeholder="请输入房间号"
            allow-clear
          />
        </FormItem>
        <FormItem label="维修类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择维修类型"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="electrical">电气维修</SelectOption>
            <SelectOption value="plumbing">水管维修</SelectOption>
            <SelectOption value="appliance">家电维修</SelectOption>
            <SelectOption value="furniture">家具维修</SelectOption>
            <SelectOption value="structure">结构维修</SelectOption>
            <SelectOption value="other">其他</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="pending">待处理</SelectOption>
            <SelectOption value="assigned">已分配</SelectOption>
            <SelectOption value="processing">处理中</SelectOption>
            <SelectOption value="completed">已完成</SelectOption>
            <SelectOption value="cancelled">已取消</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="优先级">
          <Select
            v-model:value="searchForm.priority"
            placeholder="请选择优先级"
            allow-clear
            style="width: 120px"
          >
            <SelectOption value="low">低</SelectOption>
            <SelectOption value="medium">中</SelectOption>
            <SelectOption value="high">高</SelectOption>
            <SelectOption value="urgent">紧急</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 工单表格 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredWorkOrders"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'workOrderNumber'">
            <Button type="link" @click="viewDetail(record)">
              {{ record.workOrderNumber }}
            </Button>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="editWorkOrder(record)">
                编辑
              </Button>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="assignWorkOrder(record)"
              >
                分配
              </Button>
              <Button
                v-if="record.status === 'assigned'"
                type="link"
                size="small"
                @click="startWorkOrder(record)"
              >
                开始
              </Button>
              <Button
                v-if="record.status === 'processing'"
                type="link"
                size="small"
                @click="completeWorkOrder(record)"
              >
                完成
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 新建/编辑工单弹窗 -->
    <Modal
      v-model:open="showAddModal"
      :title="isEdit ? '编辑维修工单' : '新建维修工单'"
      width="700px"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <Form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="房间号" name="roomNumber">
              <Select
                v-model:value="form.roomNumber"
                placeholder="选择房间"
                show-search
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.roomNumber"
                >
                  {{ room.roomNumber }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="报修类型" name="type">
              <Select v-model:value="form.type" placeholder="选择报修类型">
                <SelectOption value="electrical">电气维修</SelectOption>
                <SelectOption value="plumbing">水管维修</SelectOption>
                <SelectOption value="appliance">家电维修</SelectOption>
                <SelectOption value="furniture">家具维修</SelectOption>
                <SelectOption value="structure">结构维修</SelectOption>
                <SelectOption value="other">其他</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="优先级" name="priority">
              <Select v-model:value="form.priority" placeholder="选择优先级">
                <SelectOption value="low">低</SelectOption>
                <SelectOption value="medium">中</SelectOption>
                <SelectOption value="high">高</SelectOption>
                <SelectOption value="urgent">紧急</SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="预计完成时间" name="estimatedTime">
              <DatePicker
                v-model:value="form.estimatedTime"
                placeholder="选择日期"
                style="width: 100%"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="问题描述" name="description">
          <Textarea
            v-model:value="form.description"
            placeholder="请详细描述问题"
            :rows="4"
          />
        </FormItem>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="联系人" name="contactPerson">
              <Input
                v-model:value="form.contactPerson"
                placeholder="联系人姓名"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="联系电话" name="contactPhone">
              <Input v-model:value="form.contactPhone" placeholder="联系电话" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="备注" name="remark">
          <Textarea
            v-model:value="form.remark"
            placeholder="备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 工单详情弹窗 -->
    <Modal
      v-model:open="showDetailModal"
      title="工单详情"
      width="800px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="工单号">
          {{ selectedWorkOrder?.workOrderNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="房间号">
          {{ selectedWorkOrder?.roomNumber }}
        </DescriptionsItem>
        <DescriptionsItem label="报修类型">
          <Tag :color="getTypeColor(selectedWorkOrder?.type)">
            {{ getTypeText(selectedWorkOrder?.type) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="优先级">
          <Tag :color="getPriorityColor(selectedWorkOrder?.priority)">
            {{ getPriorityText(selectedWorkOrder?.priority) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="状态">
          <Tag :color="getStatusColor(selectedWorkOrder?.status)">
            {{ getStatusText(selectedWorkOrder?.status) }}
          </Tag>
        </DescriptionsItem>
        <DescriptionsItem label="维修人员">
          {{ selectedWorkOrder?.technician || '未分配' }}
        </DescriptionsItem>
        <DescriptionsItem label="创建时间">
          {{ selectedWorkOrder?.createdAt }}
        </DescriptionsItem>
        <DescriptionsItem label="预计完成时间">
          {{ selectedWorkOrder?.estimatedTime }}
        </DescriptionsItem>
        <DescriptionsItem label="联系人">
          {{ selectedWorkOrder?.contactPerson }}
        </DescriptionsItem>
        <DescriptionsItem label="联系电话">
          {{ selectedWorkOrder?.contactPhone }}
        </DescriptionsItem>
        <DescriptionsItem label="问题描述" :span="2">
          {{ selectedWorkOrder?.description }}
        </DescriptionsItem>
        <DescriptionsItem label="备注" :span="2">
          {{ selectedWorkOrder?.remark || '无' }}
        </DescriptionsItem>
      </Descriptions>
    </Modal>

    <!-- 分配工单弹窗 -->
    <Modal
      v-model:open="showAssignModal"
      title="分配维修工单"
      width="500px"
      @ok="handleAssign"
      @cancel="showAssignModal = false"
    >
      <Form
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        layout="vertical"
      >
        <FormItem label="维修人员" name="technicianId">
          <Select
            v-model:value="assignForm.technicianId"
            placeholder="选择维修人员"
          >
            <SelectOption
              v-for="technician in availableTechnicians"
              :key="technician.id"
              :value="technician.id"
            >
              {{ technician.name }} ({{ technician.specialty.join(', ') }})
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem label="预计开始时间" name="startTime">
          <DatePicker
            v-model:value="assignForm.startTime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="备注" name="assignRemark">
          <Textarea
            v-model:value="assignForm.assignRemark"
            placeholder="分配备注"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.work-orders-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.table-card {
  margin-bottom: 16px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: 500;
}
</style>
